package com.gigi.searchcenterbackendmaster.job.once;

import cn.hutool.core.collection.CollUtil;
import com.gigi.searchcenterbackendmaster.esdao.ArticleEsDao;
import com.gigi.searchcenterbackendmaster.model.dto.ArticleEsDTO;
import com.gigi.searchcenterbackendmaster.model.entity.ArticleEntity;
import com.gigi.searchcenterbackendmaster.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全量同步文章数据到 ES
 *
 * @author Gigi
 * @date 2024/8/24 22:35
 */
@Slf4j
@Component
public class FullSyncArticleToEs implements CommandLineRunner {

    @Resource
    private ArticleService articleService;

    @Resource
    private ArticleEsDao articleEsDao;

    /**
     * 项目启动时执行
     *
     * @param args
     */
    @Override
    public void run(String... args) {
        List<ArticleEntity> list = articleService.list();
        if (CollUtil.isEmpty(list)) {
            return;
        }
        List<ArticleEsDTO> articleEsDTOS = list.stream().map(ArticleEsDTO::entityToDTO).collect(Collectors.toList());
        int total = list.size();
        final int pageSize = 500;
        log.info("Start to full sync {} articles to ES", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("Syncing articles from {} to {}", i, end);
            articleEsDao.saveAll(articleEsDTOS.subList(i, end));
        }
        log.info("Finish full sync {} articles to ES", total);
    }

}
